package com.tongtong.stscommon.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.tongtong.stscommon.enumration.Message;
import com.tongtong.stscommon.enumration.Status;
import com.tongtong.stscommon.exception.STSQiniuOperationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 七牛云工具类
 */
@Component
public class QiniuUtil {

	@Autowired
	private UploadManager uploadManager;

	@Autowired
	private Auth auth;

	@Value("${oss.qiniu.bucketName}")
	private String bucketName;

	@Value("${oss.qiniu.bucketPath}")
	private String bucketPath;

	/**
	 * 上传至七牛云
	 */
	public Map<String,Object> Upload(InputStream file, String key) throws QiniuException {
		String token = auth.uploadToken(bucketName);
		Response res = uploadManager.put(file,key,token,null,null);
		DefaultPutRet putRet = new Gson().fromJson(res.bodyString(),DefaultPutRet.class);
		if(! res.isOK()) {
			throw new STSQiniuOperationException(Status.UploadFileFailed,Message.UploadFileFailed);
		}
		Map<String,Object> map = new HashMap<>();
		map.put("url","http://"+bucketPath+"/"+key);
		map.put("putRet",putRet);
		return map;
	}

	/**
	 * 删除文件
	 */
	public void Delete(String key) throws Exception {
		Configuration cfg = new Configuration(Region.huanan());
		BucketManager bucketManager = new BucketManager(auth, cfg);
		//检查目标文件是否存在
		try {
			FileInfo fileInfo = bucketManager.stat(bucketName, key);
		} catch (QiniuException e) {
			throw new STSQiniuOperationException(Status.DeleteFileFailed, Message.ObjectCanNotFound);
		}
		Response response = bucketManager.delete(bucketName, key);
		//检查响应状态码，如果成功则不做处理，否则抛出异常
		if (response.statusCode != 200) {
			throw new STSQiniuOperationException(Status.DeleteFileFailed, Message.DeleteFileFailed);
		}
	}
}
